package com.bt.lms.ui.action.registration.stu;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.RegStuBizTypeConstant;
import com.bt.lms.entity.RegStuInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.stu.PageAddStuInfo;
import com.bt.lms.ui.page.stu.vo.RegistrationStuVo;
import com.sun.org.apache.bcel.internal.generic.NEW;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


/**
 * 添加学生信息界面选择学历证书按钮事件
 */
public class PageAddStuSelectEduBookBtnAction implements EventHandler {


    @Override
    public void handle(Event event) {

        //选择学历证书文件选择器
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择学历证书");
        File eduFilePath = fileChooser.showOpenDialog(null);

        String fileName = null;
        try {
            fileName = eduFilePath.getName();
        } catch (Exception e) {
            return;
        }
        //如果文件格式不是 jpg jpeg gif pdf png 弹窗   !非
        if (!fileName.endsWith(".jpg") && !fileName.endsWith(".jpeg") && !fileName.endsWith(".gif") && !fileName.endsWith(".pdf") && !fileName.endsWith(".png")) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("文件格式有误，仅支持 jpg、jpeg、gif、pdf、png");
            alert.showAndWait();
        }
        int fileLength = fileName.length();//获取文件大小
        if (fileLength > 50) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("文件大小不能超过50MB");
            alert.showAndWait();

        }

        try {
            //读取文件流.
            FileInputStream fileIn = new FileInputStream(eduFilePath);
            byte[] buffer = new byte[1024];
            fileIn.read(buffer);

            //文件集合
            List<String> fileUrls = new ArrayList<>();
            fileUrls.add(eduFilePath.toString());

            RegistrationStuVo registrationStuVo = new RegistrationStuVo();
            registrationStuVo.setUrl(fileUrls);

            //组包
            byte[] bytes = getBytes(eduFilePath);

            //获取网络
            Socket socket = getSocket();

            //发送请求消息
            boolean sendReqMsg = sendReqMsg(bytes, socket, eduFilePath);


        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 发送请求消息
     *
     * @param bytes  bytes
     * @param socket 网
     * @return 是否成功
     */
    private boolean sendReqMsg(byte[] bytes, Socket socket, File eduFilePath) {

        try {
            //输出流
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            //接收响应消息
            RespMsg acceptReqMsg = acceptRespMsg(socket, eduFilePath);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 接收响应消息
     *
     * @param eduFilePath 文件路径
     * @return 响应消息
     */
    private RespMsg acceptRespMsg(Socket socket, File eduFilePath) {


        RespMsg respMsg = null;
        //输入流
        try {
            InputStream in = socket.getInputStream();
            byte[] buffer = new byte[1024];

            in.read(buffer);

            //响应消息
            respMsg = RespMsg.toRespMsg(buffer);
            String data = respMsg.getData();
            //如果数据不是空，弹出框显示
            if (data != null) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("学历证书上传");
                alert.setContentText("学历证书上传成功，请查看");
                alert.show();


                //让路径显示给图像 ，需要url
                String url = "file:" + File.separator + eduFilePath.toString();

                File file = new File(url);
                Image image = new Image(file.toString());
                ImageView eduFilePathImV = new ImageView(image);

                eduFilePathImV.setFitWidth(300);
                eduFilePathImV.setFitHeight(200);
                //添加到主界面
                ObservableList<Node> children = PageAddStuInfo.eduBackgroundHBox.getChildren();
                if (children.size() == 2) {
                    children.add(1, eduFilePathImV);

                } else if (children.size() == 3) {
                    children.set(1, eduFilePathImV);

                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return respMsg;
    }

    /**
     * 获取网络
     *
     * @return 网络
     */
    private Socket getSocket() {


        String ip = "127.0.0.1";
        Integer port = 8888;
        Socket socket = null;

        try {
            socket = new Socket(ip, port);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return socket;
    }

    /**
     * 组包
     *
     * @param eduFilePath 学历文件路径
     * @return byte数组
     */
    private byte[] getBytes(File eduFilePath) {

        //请求消息
        ReqMsg reqMsg = new ReqMsg();

        //报名学员信息
        RegStuInfo regStuInfo = new RegStuInfo();

        //给他，赋值
        regStuInfo.setEduUrl(eduFilePath.toString());

        //业务类型
        reqMsg.setBizType(RegStuBizTypeConstant.STU_REG_INFO_ADD);

        String filePathStr = JSON.toJSONString(regStuInfo);

        //数据带走

        reqMsg.setData(filePathStr);


        byte[] bytes = reqMsg.toBytes();


        return bytes;


    }


}

